package com.harmony.pilot.completion.client;

import com.harmony.pilot.common.dto.CodeContext;
import com.harmony.pilot.common.dto.CompletionItem;
import com.harmony.pilot.common.dto.LLMRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.Collections;
import java.util.List;

/**
 * LLM服务客户端
 */
@Slf4j
@Component
public class LLMServiceClient {
    
    private final WebClient webClient;
    
    public LLMServiceClient(@Value("${service.llm.url}") String llmServiceUrl) {
        this.webClient = WebClient.builder()
                .baseUrl(llmServiceUrl)
                .build();
    }
    
    /**
     * 使用LLM增强补全
     */
    public List<CompletionItem> enhanceCompletions(CodeContext context, List<CompletionItem> existingItems) {
        try {
            String prompt = buildPrompt(context, existingItems);
            
            LLMRequest request = LLMRequest.builder()
                    .prompt(prompt)
                    .systemPrompt("You are a C++ code completion assistant for OpenHarmony project.")
                    .temperature(0.3)
                    .maxTokens(500)
                    .build();
            
            return webClient.post()
                    .uri("/llm/complete")
                    .bodyValue(request)
                    .retrieve()
                    .bodyToFlux(CompletionItem.class)
                    .collectList()
                    .block();
        } catch (Exception e) {
            log.error("Failed to enhance completions with LLM", e);
            return Collections.emptyList();
        }
    }
    
    private String buildPrompt(CodeContext context, List<CompletionItem> items) {
        StringBuilder sb = new StringBuilder();
        sb.append("Complete the following C++ code:\n\n");
        sb.append("File: ").append(context.getFilePath()).append("\n");
        sb.append("Prefix:\n").append(context.getPrefix()).append("\n");
        sb.append("Cursor position: line ").append(context.getCursorLine())
          .append(", column ").append(context.getCursorColumn()).append("\n\n");
        sb.append("Provide intelligent completions based on the context.");
        return sb.toString();
    }
}

